from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache

class TokenResponseMixin(MiddlewareMixin):

    def process_response(self, request, response):
        if request.user.is_anonymous:
            return response
        access_token = cache.get(f"{request.user.id}:access_token")
        if access_token and response:
            try:
                response.data['access_token'] = access_token
                #需要重新render才能使修改生效 
                response._is_rendered = False
                response.render()
            except (AttributeError, TypeError):
                pass
        return response
